import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/http/url_helper.dart';
import 'package:leader_doctor_flutter/common/utils/date_utils.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/refresh_custom_widget.dart';
import 'package:leader_doctor_flutter/common/widget/table_placeholder_widget.dart';
import 'package:leader_doctor_flutter/model/my_project_outcome_model.dart';
import 'package:leader_doctor_flutter/model/my_project_outcome_top_tabbar.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MyProjectOutcomePage extends StatefulWidget {
  const MyProjectOutcomePage({super.key});

  @override
  State<MyProjectOutcomePage> createState() => _MyProjectOutcomePageState();
}

class _MyProjectOutcomePageState extends State<MyProjectOutcomePage>
    with SingleTickerProviderStateMixin {
  var pageSize = 20;
  var pageNo = 1;
  bool dataLoaded = false; // 数据请求中

  String tabbarKey = "";
  String tabbarName = "";

  List<MyProjectOutcomeTopTabbarModel> topTabbarArray = [];
  List<MyProjectOutcomeModel> dataArray = [];

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    pageNo = 1;
    _getProjectOutcomeList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    pageNo++;
    _getProjectOutcomeList();
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    _initializeData();
    super.initState();
  }

  _initializeData() async {
    await _getProjectOutcomeTopTabbar();
    await _getProjectOutcomeList();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return contentView();
  }

  Widget contentView() {
    return DefaultTabController(
        length: topTabbarArray.length,
        child: Scaffold(
          appBar: CommWidget.getCommAppbar(context),
          body: Container(
            // width: double.infinity,
            color: ColorRes.white,
            child: Column(
              children: [
                Container(
                  child: myTabBar(),
                ),
                SizedBox(
                  height: 10.w,
                  child: Container(color: Color(0xFFF2F2F2)),
                ),
                Expanded(
                  child: PageView(
                    physics: NeverScrollableScrollPhysics(),
                    children: topTabbarArray.map((tab) {
                      return SmartRefresher(
                        controller: _refreshController,
                        enablePullDown: true,
                        enablePullUp: true,
                        onRefresh: _onRefresh,
                        onLoading: _onLoading,
                        header: RefreshCustomHeaderWidget(),
                        footer: RefreshCustomFooterWidget(),
                        child: dataLoaded
                            ? dataArray.isEmpty
                                ? TablePlaceholderWidget(
                                    message: "您还没有${tabbarName}项目成果哦",
                                    yOffset: -30,
                                  )
                                :
                                // ListPage(
                                //     dataArray: dataArray,
                                //     topTabbarKey: tab.value ?? "",
                                //   )
                                ListView.builder(
                                    itemCount: dataArray.length,
                                    itemBuilder:
                                        (BuildContext context, int index) {
                                      return _buildListItem(
                                          dataArray[index], tabbarKey);
                                    },
                                  )
                            : Container(),
                      );
                    }).toList(),
                  ),

                  // child: SmartRefresher(
                  //   controller: _refreshController,
                  //   enablePullDown: true,
                  //   enablePullUp: true,
                  //   onRefresh: _onRefresh,
                  //   onLoading: _onLoading,
                  //   header: RefreshCustomHeaderWidget(),
                  //   footer: RefreshCustomFooterWidget(),
                  //   child: dataLoaded
                  //       ? dataArray.isEmpty
                  //           ? TablePlaceholderWidget(
                  //               message: "暂无数据",
                  //               yOffset: -30,
                  //             )
                  //           : PageView(
                  //               physics: NeverScrollableScrollPhysics(),
                  //               children: topTabbarArray.map((tab) {
                  //                 return ListPage(
                  //                     dataArray: dataArray,
                  //                     topTabbarKey: tab.value ?? "");
                  //               }).toList(),
                  //             )
                  //       : Container(),
                  // ),
                ),
              ],
            ),
          ),
        ));
  }

  Widget _buildListItem(MyProjectOutcomeModel model, String tabbarKey) {
    String title = model.title ?? "";
    String coverImg = model.coverImg ?? "";
    String time = model.createTime ?? "";
    String authorName = model.authorName ?? "";
    print("顶部tab = $tabbarKey");
    if (tabbarKey == "online_meeting") {
      // 线上会议
      time = MyDateUtils.timeStringToSpecifiedFormatTimeString(
          time, "yyyy-MM-dd HH:mm");
    } else if (tabbarKey == "live") {
      // 直播
      time = MyDateUtils.timeStringToSpecifiedFormatTimeString(
          time, "yyyy-MM-dd HH:mm");
    } else if (tabbarKey == "video") {
      // 视频
      time =
          MyDateUtils.timeStringToSpecifiedFormatTimeString(time, "YYYY.MM.dd");
      time = authorName + ' | ' + time;
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque, // 点击空白处也可以响应
      onTap: () => _jumpDetail(model),
      child: Container(
        height: 90.w,
        margin: EdgeInsets.only(top: 10.w, bottom: 5.w),
        padding: EdgeInsets.symmetric(horizontal: 10.w),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: 90.w,
              height: 90.w,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.w), // 圆角为6
                color: ColorRes.colorF2F2F2, // 灰色背景
              ),
              child: Stack(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(6.w), // 添加圆角
                    child: ImageLoader.loadImage("${coverImg}",
                        size: Size(90.w, 90.w),
                        fit: BoxFit.cover,
                        errorImg: "assets/images/icon_default_img.webp"),
                  ),
                  Positioned.fill(
                      child: Center(
                    child: ImageLoader.loadAsset("icon_video_play.webp", 25.w),
                  ))
                ],
              ),
            ),
            SizedBox(width: 10.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '${title}',
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis, // 可选，超出部分以省略号表示
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: ColorRes.color333333, // 黑色标题
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    '${time}',
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: ColorRes.color9A9A9A, // 红色时间
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 调转到详情
  _jumpDetail(MyProjectOutcomeModel model) async {
    String? detailsUrl = model.infoUrl;
    if (detailsUrl != null) {
      detailsUrl += "&hiddenNavigation=1";
    }
    UrlHelper.loadH5Page(null, detailsUrl ?? "");
  }

  Widget myTabBar() {
    return TabBar(
      tabs: topTabbarArray.map((e) => Tab(text: e.name)).toList(),
      onTap: (index) {
        MyProjectOutcomeTopTabbarModel model = topTabbarArray[index];
        tabbarKey = model.value ?? "";
        tabbarName = model.name ?? "";
        print("object = ${model.value}");
        pageNo = 1;
        _getProjectOutcomeList();
      },
      isScrollable: false, //是否可以滑动，标题左右滑动
      padding: EdgeInsets.only(top: 1.w, left: 10.w, right: 10.w),
      indicatorWeight: 1.w, //指示器高度
      indicator: UnderlineTabIndicator(
        borderSide: BorderSide(width: 2.w, color: ColorRes.colorMain), //高度和颜色
        borderRadius: BorderRadius.all(Radius.circular(1.w)),
        insets: EdgeInsets.only(left: 40.w, right: 40.w), //左右间距反向设置长度
      ),
      labelColor: ColorRes.colorMain, //标题选择时颜色
      unselectedLabelColor: ColorRes.color333333, //未被选择时颜色
      labelStyle: TextStyle(fontSize: 14.sp), //被选择时label风格样式
    );
  }

  /// 获取项目成果顶部tabbar
  _getProjectOutcomeTopTabbar() async {
    var user = App.instance.userInfo;
    var httpRequest = HttpRequest(Api.projectOutcomeTopTab, urlParams: {});
    var httpResponse = await HttpClient.get(httpRequest);
    var map = jsonDecode(utf8.decode(httpResponse.raw!.bodyBytes));
    var tmpList = ((map['responseBody'] as List?) ?? [])
        .map((e) => MyProjectOutcomeTopTabbarModel.fromJson(e))
        .toList();
    topTabbarArray.addAll(tmpList);
    setState(() {
      if (topTabbarArray.isNotEmpty) {
        MyProjectOutcomeTopTabbarModel model = topTabbarArray[0];
        tabbarKey = model.value ?? "";
      }
    });
  }

  /// 获取项目成果列表
  _getProjectOutcomeList() async {
    var user = App.instance.userInfo;
    print("项目成果列表tabbarKey：${tabbarKey}");
    var httpRequest = HttpRequest(Api.projectOutcomeList, body: {
      'medicalId': user?.id,
      "projectType": tabbarKey,
      "pageIndex": pageNo.toString(),
      "pageSize": pageSize.toString()
    });
    var httpResponse = await HttpClient.postJson(httpRequest);
    var map = jsonDecode(utf8.decode(httpResponse.raw!.bodyBytes));
    print("项目成果列表：${map}");
    var tmpList = ((map['responseBody'] as List?) ?? [])
        .map((e) => MyProjectOutcomeModel.fromJson(e))
        .toList();
    if (tmpList.length < pageSize) {
      print("tmpList.length < pageSize");
      _refreshController.loadNoData();
    } else {
      print("tmpList.length >= pageSize");
      _refreshController.loadComplete();
    }
    pageNo == 1 ? dataArray = tmpList : dataArray.addAll(tmpList);
    setState(() {
      dataLoaded = true;
    });
  }
}

// class ListPage extends StatelessWidget {
//   final List<MyProjectOutcomeModel> dataArray;
//   final String topTabbarKey;

//   const ListPage({required this.dataArray, required this.topTabbarKey});

//   @override
//   Widget build(BuildContext context) {
//     return ListView.builder(
//       itemCount: dataArray.length,
//       itemBuilder: (BuildContext context, int index) {
//         return _buildListItem(dataArray[index], topTabbarKey);
//       },
//     );
//     // return SingleChildScrollView(
//     //   child: Column(
//     //     children: dataArray
//     //         .map((model) => _buildListItem(model, topTabbarKey))
//     //         .toList(),
//     //   ),
//     // );
//   }

//   Widget _buildListItem(MyProjectOutcomeModel model, String tabbarKey) {
//     String title = model.title ?? "";
//     String coverImg = model.coverImg ?? "";
//     String time = model.createTime ?? "";
//     String authorName = model.authorName ?? "";

//     if (tabbarKey == "online_meeting") {
//       // 线上会议
//       time = MyDateUtils.timeStringToSpecifiedFormatTimeString(
//           time, "yyyy-MM-dd HH:mm");
//     } else if (tabbarKey == "live") {
//       // 直播
//       time = MyDateUtils.timeStringToSpecifiedFormatTimeString(
//           time, "yyyy-MM-dd HH:mm");
//     } else if (tabbarKey == "video") {
//       // 视频
//       time =
//           MyDateUtils.timeStringToSpecifiedFormatTimeString(time, "YYYY.MM.dd");
//       time = authorName + ' | ' + time;
//     }

//     return Container(
//       margin: EdgeInsets.only(top: 10.w),
//       padding: EdgeInsets.symmetric(horizontal: 10.w),
//       decoration: BoxDecoration(
//         color: ColorRes.colorFFFFFF, // 白色背景
//         borderRadius: BorderRadius.circular(6.w), // 圆角为6
//       ),
//       child: Row(
//         crossAxisAlignment: CrossAxisAlignment.start,
//         children: [
//           Container(
//             width: 90.w,
//             height: 90.w,
//             decoration: BoxDecoration(
//               borderRadius: BorderRadius.circular(6.w), // 圆角为6
//               color: ColorRes.colorF2F2F2, // 灰色背景
//             ),
//             child: Stack(
//               children: [
//                 ImageLoader.loadImage("${coverImg}",
//                     size: Size(90.w, 90.w),
//                     fit: BoxFit.cover,
//                     errorImg: "assets/images/icon_default_img.webp"),
//                 Positioned.fill(
//                     child: Center(
//                   child: ImageLoader.loadAsset("icon_video_play.webp", 25.w),
//                 ))
//               ],
//             ),
//           ),
//           SizedBox(width: 10.w), // 左侧灰色背景和标题的间距
//           Expanded(
//             child: Column(
//               crossAxisAlignment: CrossAxisAlignment.start,
//               children: [
//                 Text(
//                   '${title}',
//                   style: TextStyle(
//                     fontSize: 14.sp,
//                     color: ColorRes.color333333, // 黑色标题
//                     fontWeight: FontWeight.bold,
//                   ),
//                 ),
//                 SizedBox(height: 45.w), // 标题和时间的间距
//                 Text(
//                   '${time}',
//                   style: TextStyle(
//                     fontSize: 13.sp,
//                     color: ColorRes.color9A9A9A, // 红色时间
//                   ),
//                 ),
//               ],
//             ),
//           ),
//         ],
//       ),
//     );
//   }
// }
